package com.dao;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.facade.RunningNumberFacade;
import com.model.RunningNumber;

public class RunningNumberDAO extends GenericDAO<RunningNumber> {

	private static final long serialVersionUID = 1L;

	public RunningNumberDAO() {
		super(RunningNumber.class);
	}
	
	public String nextRunningNumber (String form){
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("formName", form);
		
		RunningNumber rn = super.findOneResult(RunningNumber.FIND_RN_BY_FORM, parameters);
		
		String returnValue = rn.getPrefix();
		int length = String.valueOf(rn.getMaxNumber()).length();
		int newCurrentNumber = rn.getCurrentNumber() + 1;
		
		if( newCurrentNumber > rn.getMaxNumber()){
			newCurrentNumber = 1;
			returnValue = returnValue.concat(StringUtils.leftPad(String.valueOf(newCurrentNumber), length, "0"));
		}else{
			returnValue = returnValue.concat(StringUtils.leftPad(String.valueOf(newCurrentNumber), length, "0"));
		}
		
		rn.setCurrentNumber(newCurrentNumber);

		RunningNumberFacade rnFacade = new RunningNumberFacade();
		rnFacade.updateRunningNumber(rn);
		
		return returnValue;
	}
	

}
